//
//  ZYCProfileRootViewController.m
//  ZDSC
//
//  Created by ZDTX on 2021/6/25.
//

#import "ZYCProfileRootViewController.h"
#import "ZYCProfileRootHeaderView.h"
#import "ZYCProfileRootCell.h"
#import "ZYCLoginRoleViewController.h"
#import "ZYCProfileUserInfomationViewController.h"
#import "ZYCProfileParentUserInfomationViewController.h"
#import "ZYCManageCourseRegistrationViewController.h"
#import "ZYCProfileStudentManagementViewController.h"
#import "ZYCModifyPasswordViewController.h"
#import "ZYCProfileSettingViewController.h"
#import "ZYCClassManagementViewController.h"
#import "ZYCLoginViewController.h"
#import "ZYCNavigationController.h"
#import "ZYCUserInfoModel.h"
#import "ZYCUserLoginModel.h"
#import "ZYCLoginOutView.h"
#import "ZYCProfileFaceEntyAlbumViewController.h"
#import "ZYCManageCourseSelectViewController.h"
#import "ZYCCourseStudentModel.h"
#import "SystemCamera.h"
#import "ZYCUserInfoModel.h"
@interface ZYCProfileRootViewController ()<UINavigationControllerDelegate,UICollectionViewDataSource,UICollectionViewDelegate,ZYCLoginOutViewDelegate,ZYCProfileRootHeaderViewDelegate>

@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic,strong) UICollectionViewFlowLayout *layout;
@property (nonatomic, strong) NSArray *dataSource;
@property (nonatomic, assign) ZYCLoginRoleType roleType;
@property (nonatomic, copy) NSString *role;
@property (nonatomic, strong) NSArray *teacherArr;
@property (nonatomic, strong) NSArray *parentArr;
@property (nonatomic, strong) ZYCUserInfoModel *userInfoModel;
@property (nonatomic, strong) ZYCLoginOutView *loginOutView;
@end

@implementation ZYCProfileRootViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self.view addSubview:self.collectionView];
    self.collectionView.contentInset = UIEdgeInsetsMake(-kStatusBarHeight-5, 0, 0, 0);
    self.collectionView.contentOffset = CGPointMake(0, kStatusBarHeight+5);
    NSInteger roleType =  [[NSUserDefaults standardUserDefaults] integerForKey:@"kUserRoleType"];
    if (roleType  == 0) {//教师
        self.roleType = ZYCLoginRoleTypeTeacher;
        self.dataSource = self.teacherArr;
    }else{
        self.roleType = ZYCLoginRoleTypeParent;
        self.dataSource = self.parentArr;
    }

}

//- (void)viewWillAppear:(BOOL)animated{
//    [super viewWillAppear:animated];
//    self.navigationController.delegate = self;
//    [self.collectionView reloadData];
//}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.delegate = self;
    NSInteger roleType =  [[NSUserDefaults standardUserDefaults] integerForKey:@"kUserRoleType"];
    if (roleType  == 0) {//教师
        self.roleType = ZYCLoginRoleTypeTeacher;
        self.dataSource = self.teacherArr;
        self.role = @"1";
    }else{
        self.roleType = ZYCLoginRoleTypeParent;
        self.dataSource = self.parentArr;
        self.role = @"2";
    }
    [self getUserInfo];
}


- (void)getUserInfo{
    NSDictionary *params = @{
        @"roleType":self.role
    };
    [MrjSVProgressHUD showWithStatus:@"加载中..."];
    [[URLManager sharedURLManager] postUrlString:Profile_Get_GetMyInfo requestService:RequestServiceSystem parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(id  _Nullable responseObject) {
        [MrjSVProgressHUD dismiss];
        if (SUCCESS(responseObject[@"code"])) {
            ZYCUserInfoModel *userInfo = [ZYCUserInfoModel yy_modelWithDictionary:responseObject[@"body"]];
            self.userInfoModel = userInfo;
            [self.collectionView reloadData];
            
        }else{
            [MrjToast makeToast:responseObject[@"message"] makeView:self.view];
        }
    } failure:^(NSError * _Nonnull error) {
        
    }];
}


// 获取用户角色
- (void)getUserRoles{
    [[URLManager sharedURLManager] getUrlString:Login_GET_userType requestService:RequestServiceSystem parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
    } success:^(id  _Nullable responseObject) {
        if (SUCCESS(responseObject[@"code"])) {
            NSArray *bodyArr = responseObject[@"body"];
            if ([bodyArr containsObject:@"1"] && [bodyArr containsObject:@"2"]) {
                ZYCLoginRoleViewController *vc = [[ZYCLoginRoleViewController alloc] init];
                [self.navigationController pushViewController:vc animated:YES];
            }else{
                [MrjToast makeToast:@"您只有一种身份,无法切换" makeView:self.view];
            }
            
        }
    } failure:^(NSError * _Nonnull error) {
        
    }];
}



#pragma mark - UINavigationControllerDelegate
-(void) navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated{
    [self.navigationController setNavigationBarHidden:[viewController isKindOfClass:[self class]] animated:YES];
}


- (void)dealloc{
    self.navigationController.delegate = nil;
}


#pragma mark - UICollectionViewDataSource && UICollectionViewDelegate
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.dataSource.count;
}


- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    ZYCProfileRootCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([ZYCProfileRootCell class]) forIndexPath:indexPath];
    cell.dict = self.dataSource[indexPath.item];
    return cell;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    ZYCProfileRootHeaderView *headerView = nil;
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:NSStringFromClass([ZYCProfileRootHeaderView class]) forIndexPath:indexPath];
        headerView.delegate = self;
        headerView.model = self.userInfoModel;
    }
    return headerView;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    [collectionView deselectItemAtIndexPath:indexPath animated:NO];
    NSDictionary *dict = self.dataSource[indexPath.item];
    if ([dict[@"title"] isEqualToString:NSLocalizedString(@"个人信息", nil)]) {
        if (self.roleType == ZYCLoginRoleTypeTeacher) {
            ZYCProfileUserInfomationViewController *vc = [ZYCProfileUserInfomationViewController new];
            [self.navigationController pushViewController:vc animated:YES];
        }else{
            ZYCProfileParentUserInfomationViewController *vc = [ZYCProfileParentUserInfomationViewController new];
            [self.navigationController pushViewController:vc animated:YES];
        }
    }else  if ([dict[@"title"] isEqualToString:NSLocalizedString(@"切换身份", nil)]) {
        [self getUserRoles];
    }else  if ([dict[@"title"] isEqualToString:NSLocalizedString(@"修改密码", nil)]) {
        ZYCModifyPasswordViewController *vc = [ZYCModifyPasswordViewController new];
        [self.navigationController pushViewController:vc animated:YES];
    }else  if ([dict[@"title"] isEqualToString:NSLocalizedString(@"选课报名", nil)]) {
        [self judegeMyStudentCount];
    }else  if ([dict[@"title"] isEqualToString:NSLocalizedString(@"设置", nil)]) {
        ZYCProfileSettingViewController *vc = [ZYCProfileSettingViewController new];
        [self.navigationController pushViewController:vc animated:YES];
    }else  if ([dict[@"title"] isEqualToString:NSLocalizedString(@"班级管理", nil)]) {
//        ZYCClassManagementViewController *vc = [ZYCClassManagementViewController new];
//        [self.navigationController pushViewController:vc animated:YES];
        [MrjToast makeToast:@"正在努力研发中..." makeView:self.view];
    }else  if ([dict[@"title"] isEqualToString:NSLocalizedString(@"学生管理", nil)]) {
        ZYCManageCourseRegistrationViewController *vc = [ZYCManageCourseRegistrationViewController new];
        vc.enterType = ZYCCourseRegistrationEnterProfileStudentManagemt;
        [self.navigationController pushViewController:vc animated:YES];
    }else if([dict[@"title"] isEqualToString:NSLocalizedString(@"退出登录", nil)]){
        // 退出登录
        [self clickloginOutAction];
    }else{
        
    }
}

// 获取所有学生
- (void)judegeMyStudentCount{
    [[URLManager sharedURLManager] getUrlString:Appliance_Get_getMyStudents requestService:RequestServiceWorkBench parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
            
        } success:^(id  _Nullable responseObject) {
            if (SUCCESS(responseObject[@"code"])) {
                NSArray *array = [NSArray yy_modelArrayWithClass:[ZYCCourseStudentModel class] json:responseObject[@"body"]];
                if (array.count > 1) {
                    ZYCManageCourseRegistrationViewController *vc = [ZYCManageCourseRegistrationViewController new];
                    vc.enterType = ZYCCourseRegistrationEnterProfileCourseRegister;
                    [self.navigationController pushViewController:vc animated:YES];
                }else{
    
                    ZYCManageCourseSelectViewController *vc = [ZYCManageCourseSelectViewController new];
                    vc.titleString = @"选课报名";
                    ZYCCourseStudentModel *model = array.firstObject;
                    vc.scope = model.scope;
                    vc.studentId = model.s_id;
                    vc.studentName = model.name;
                    [self.navigationController pushViewController:vc animated:YES];
                }
      
            }
        } failure:^(NSError * _Nonnull error) {
            
        }];
}

#pragma mark - ZYCProfileRootHeaderViewDelegate
- (void)profileRootHeaderViewDidClickHeader{
    ZYCWeakSelf
    [SystemCamera sharedSystemCamera].SelectImage = ^(UIImage *headerImage, NSInteger buttonIndex) {
        ZYCProfileFaceEntyAlbumViewController *vc = [[ZYCProfileFaceEntyAlbumViewController alloc] init];
        vc.headerImage = headerImage;
        if (buttonIndex == 0) {
            vc.type = ZYCProfileFaceEntryViewTypePhoto;
        }else{
            vc.type = ZYCProfileFaceEntryViewTypeAlbum;
        }
        [weakSelf.navigationController pushViewController:vc animated:YES];
    };

    [SystemCamera cameraWillShowInController:self];
}



#pragma mark - getters

- (NSArray *)dataSource {
    if (!_dataSource) {
        _dataSource = [NSArray array];
    }
    return _dataSource;
}


- (NSArray *)teacherArr {
    if (!_teacherArr) {
        _teacherArr =  @[
            @{@"title":NSLocalizedString(@"个人信息", nil),@"imgName":@"grxx"},
            @{@"title":NSLocalizedString(@"班级管理", nil),@"imgName":@"bjgl"},
            @{@"title":NSLocalizedString(@"切换身份", nil),@"imgName":@"qhsf"},
            @{@"title":NSLocalizedString(@"修改密码", nil),@"imgName":@"xgmm"},
            @{@"title":NSLocalizedString(@"设置", nil),@"imgName":@"sz"},
            @{@"title":NSLocalizedString(@"退出登录", nil),@"imgName":@"tcdl"}];
    }
    return _teacherArr;
}

- (NSArray *)parentArr {
    if (!_parentArr) {
        _parentArr =  @[
            @{@"title":NSLocalizedString(@"个人信息", nil),@"imgName":@"grxx"},
            @{@"title":NSLocalizedString(@"学生管理", nil),@"imgName":@"bjgl"},
            @{@"title":NSLocalizedString(@"切换身份", nil),@"imgName":@"qhsf"},
            @{@"title":NSLocalizedString(@"选课报名", nil),@"imgName":@"xkbm-1"},
            @{@"title":NSLocalizedString(@"设置", nil),@"imgName":@"sz"},
            @{@"title":NSLocalizedString(@"修改密码", nil),@"imgName":@"xgmm"},
            @{@"title":NSLocalizedString(@"退出登录", nil),@"imgName":@"tcdl"}];
    }
    return _parentArr;
}

- (UICollectionView *)collectionView{
    if (!_collectionView) {
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight - kTabBarHeight) collectionViewLayout:self.layout];
        _collectionView.dataSource = self;
        _collectionView.delegate = self;
        _collectionView.scrollEnabled = YES;
        _collectionView.backgroundColor = [UIColor groupTableViewBackgroundColor];
        [_collectionView registerClass:[ZYCProfileRootCell class]            forCellWithReuseIdentifier:NSStringFromClass([ZYCProfileRootCell class])];
        [_collectionView registerClass:[ZYCProfileRootHeaderView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:NSStringFromClass([ZYCProfileRootHeaderView class])];
        _collectionView.showsVerticalScrollIndicator = NO;

    }
    return _collectionView;
}

- (UICollectionViewFlowLayout *)layout{
    if (!_layout) {
        _layout = [[UICollectionViewFlowLayout alloc] init];
        _layout.itemSize = CGSizeMake(154,78);
        _layout.scrollDirection = UICollectionViewScrollDirectionVertical;
        _layout.headerReferenceSize = CGSizeMake(kScreenWidth, 300.0f);
        _layout.minimumLineSpacing = 23.0;//行间距
        _layout.minimumInteritemSpacing = 20.0f;
        _layout.sectionInset = UIEdgeInsetsMake(10, 23, 20, 21);
    }
    return _layout;
}


//登出
-(void)loginout{
    [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"kLoginFlag"];
    [[NSUserDefaults standardUserDefaults] setObject:@"" forKey:@"Authorization"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    ZYCLoginViewController *vc = [[ZYCLoginViewController alloc] init];
    ZYCNavigationController *nav = [[ZYCNavigationController alloc] initWithRootViewController:vc];
    [UIApplication sharedApplication].keyWindow.rootViewController = nav;
    [[UIApplication sharedApplication].keyWindow makeKeyAndVisible];
}



- (void)clickloginOutAction{
    [self.loginOutView show];
}


- (ZYCLoginOutView *)loginOutView {
    if (!_loginOutView) {
        _loginOutView = [[ZYCLoginOutView alloc] initWithFrame:CGRectMake(0, 0, 280.0f, 155.0f)];
        _loginOutView.delegate = self;
        _loginOutView.title = @"提醒";
        _loginOutView.content = @"确认是否退出登录!";
        [self.tabBarController.view addSubview:_loginOutView];
    }
    return _loginOutView;
}


#pragma mark - ZYCLoginOutViewDelegate

- (void)loginOutViewDidClickLogout{
    [self loginout];
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
